package com.github.netty.config;


import com.github.netty.context.NettyApplicationContext;
import com.github.netty.handler.DefaultNettyServerHandler;
import com.github.netty.properties.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;

import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ObjectUtils;


/**
 * @author ArchieSean
 * @description 抽象配置，防止没有自定义配置
 * @date 2024-08-14
 */
public abstract class AbstractAbstractNettyConfigurer implements IServerConfig {

    private static final Log logger = LogFactory.getLog(AbstractAbstractNettyConfigurer.class);

    private final DefaultNettyServerHandler simpleChannelInboundHandler;

    private final NettyProperties nettyProperties;
    public AbstractAbstractNettyConfigurer() {
      this.simpleChannelInboundHandler= NettyApplicationContext.getBean(DefaultNettyServerHandler.class);
      this.nettyProperties= NettyApplicationContext.getBean(NettyProperties.class);
    }

    /**
     * 避免ServerBootstrap对外暴露
     * @param bootstrap bootstrap
     */
    @Override
    public void config(ServerBootstrap bootstrap) {
        logger.info("使用默认配置bootstrap，配置了：SO_BACKLOG,SO_KEEPALIVE=true");
        //添加默认配置,等待队列大小
        bootstrap.option(ChannelOption.SO_BACKLOG,
                ObjectUtils.isEmpty(nettyProperties.getWaitSize())?
                128:nettyProperties.getWaitSize());
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
    }


    /***
     *
     * @param pipeline 流水线
     */
    @Override
    public void configurePipeline(ChannelPipeline pipeline) {
        //http服务器编解码器
        pipeline.addLast(new HttpServerCodec());
        //聚合http消息,设置最大消息长度: 64kb
        pipeline.addLast(new HttpObjectAggregator(
                ObjectUtils.isEmpty(nettyProperties.getMsgLength())?64 * 1024: nettyProperties.getMsgLength())
        );
        //业务处理类
        pipeline.addLast(simpleChannelInboundHandler);
        //netty连接地址
        pipeline.addLast(new WebSocketServerProtocolHandler(nettyProperties.getUrl()));
    }
}
